
/**
 *
 * @author ARIJIT PAL
 */


import com.apps.controllers.CustomInputStream;
import com.jcraft.jsch.*;
import java.io.InputStream;
import java.util.Scanner;
import javax.swing.*;

public class Shell{
  public static void main(String[] arg){

    try{
      JSch jsch=new JSch();
      System.out.println("Start:");
      String host=null;
      if(arg.length>0){
        host=arg[0];
      }
      else{
        host=JOptionPane.showInputDialog("Enter username@hostname",
                                         "sshuser"+
                                         "@localhost");
      }
      String user=host.substring(0, host.indexOf('@'));
      host=host.substring(host.indexOf('@')+1);

      Session session=jsch.getSession(user, host, 22);

      String passwd = JOptionPane.showInputDialog("Enter password","test123");
      session.setPassword(passwd);

      UserInfo ui = new MyUserInfo();

      session.setUserInfo(ui);
      session.connect(30000);   // making a connection with timeout.

      Channel channel=session.openChannel("shell");

      InputStream in=channel.getInputStream();

      CustomInputStream ins = new CustomInputStream(30,channel);
      channel.setInputStream(/*System.in*/ins);
            
      //channel.connect();
      channel.connect();
      byte[] tmp=new byte[1024];
      while(true){
        //start output thread
        ins.startCmdOut();

        if(channel.isClosed()){
          System.out.println("exit-status: "+channel.getExitStatus());
          break;
        }

        Scanner scn = new Scanner(System.in);
        System.out.print("Enter CMD:");
        String cmdin = scn.nextLine();
        if(!cmdin.contains("cmd@"))
        {
            ins.setCommand(cmdin);
        }else{
            cmdin = cmdin.split("cmd@").length>0?cmdin.split("cmd@")[1]:"\n";
            String cmdout = ins.getOutput(cmdin, 0, "arijitpal");
            System.out.println("OUTPUT <"+cmdout+">");
        }
      }
     // channel.disconnect();
     // session.disconnect();
    }
    catch(Exception e){
      System.out.println(e);
    }
  }

  public static class MyUserInfo
                          implements UserInfo, UIKeyboardInteractive{
    public String getPassword(){ return null; }
    public boolean promptYesNo(String str){ System.out.println(str);
          return true; }
    public String getPassphrase(){ return null; }
    public boolean promptPassphrase(String message){ return false; }
    public boolean promptPassword(String message){ return false; }
    public void showMessage(String message){ System.out.println(message); }
    public String[] promptKeyboardInteractive(String destination,
                                              String name,
                                              String instruction,
                                              String[] prompt,
                                              boolean[] echo){
      return null;
    }
  }
}